<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品编码" prop="goodsId">
        <el-input
          v-model="queryParams.goodsId"
          placeholder="请输入商品编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账单名称" prop="billName">
        <el-input
          v-model="queryParams.billName"
          placeholder="请输入账单名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品串号" prop="goodsSn">
        <el-input
          v-model="queryParams.goodsSn"
          placeholder="请输入商品串号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="待审核" :value="1" />
          <el-option label="已审核" :value="2" />
          <el-option label="退货" :value="3" />
          <el-option label="作废" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
          <el-option label="商品出售" :value="1" />
          <el-option label="自定义账单" :value="2" />
          <el-option label="退货账单" :value="3" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-printer"
          size="mini"
          @click="gotoPrinting"
          :disabled="multiple"
        >出账单</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="billList" @selection-change="handleSelectionChange" :row-class-name="setRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="账单编号" align="center" prop="billId" />
      <el-table-column label="商品编码" align="center" prop="goodsId" />
      <el-table-column label="账单名称" align="center" prop="billName">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)" class="link-type">{{scope.row.billName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售价" align="center" prop="sellPrice" />
      <el-table-column label="利润" align="center" prop="profit" />
      <el-table-column label="收款账户" align="center" prop="payee" :formatter="payeeFormatter" />
      <el-table-column label="账单类型" align="center" prop="type" :formatter="typeFormatter" />
      <el-table-column label="支付方式" align="center" prop="paymentType" width="100">
        <template slot-scope="scope">
          <el-tag
            v-for="payment in paymentTypeOptions"
            v-if="payment.value === scope.row.paymentType"
            :type="payment.type"
          >
            {{payment.label}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1">待审核</el-tag>
          <el-tag type="success" v-else-if="scope.row.status === 2">已审核</el-tag>
          <el-tag type="warning" v-else-if="scope.row.status === 3">退货</el-tag>
          <el-tag type="danger" v-else>作废</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="销售人" align="center" prop="sellBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--goodsDetail-->
    <el-dialog title="商品详情" :visible.sync="detailOpen" width="60%" append-to-body>
      <el-form v-if="detailInfo != null" label-width="80px">
        <el-row>
          <el-col :span="12" v-if="detailInfo.goodsInfo != null">
            <el-form-item label="商品编码: " style="margin: 2px">{{detailInfo.goodsInfo.goodsId}}</el-form-item>
            <el-form-item label="商品名称: " style="margin: 2px">{{detailInfo.goodsInfo.goodsName}}</el-form-item>
          </el-col>
          <el-col :span="12" v-if="detailInfo.goodsInfo != null">
            <el-form-item label="串号: " style="margin: 2px">{{detailInfo.goodsInfo.goodsSn}}</el-form-item>
            <el-form-item label="规格: " style="margin: 2px">{{detailInfo.goodsInfo.printing}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <div v-if="detailInfo.goodsInfo != null">
              <el-form-item label="验机人: " style="margin: 2px">{{userFormatter(detailInfo.goodsInfo.testUserId)}}</el-form-item>
              <el-form-item label="验机时间: " style="margin: 2px">{{detailInfo.goodsInfo.testTime}}</el-form-item>
            </div>
            <el-form-item label="成本价: " style="margin: 2px">{{detailInfo.row.costPrice}}</el-form-item>
            <el-form-item label="类型: " style="margin: 2px">{{typeFormatter(detailInfo.row)}}</el-form-item>
            <el-form-item label="修改人: " style="margin: 2px">{{detailInfo.row.updateBy}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <div v-if="detailInfo.goodsInfo != null">
              <el-form-item label="仓库: " style="margin: 2px">{{stockFormatter(detailInfo.goodsInfo.stockId)}}</el-form-item>
              <el-form-item label="仓位: " style="margin: 2px">{{detailInfo.goodsInfo.stockNum}}</el-form-item>
            </div>
            <el-form-item label="创建人: " style="margin: 2px">{{detailInfo.row.createBy}}</el-form-item>
            <el-form-item label="报价师: " style="margin: 2px" v-if="detailInfo.collectInfo != null">{{offerNameFormat(detailInfo.collectInfo)}}</el-form-item>
            <el-form-item label="修改时间: " style="margin: 2px">{{detailInfo.row.updateTime}}</el-form-item>
          </el-col>

          <el-col :span="24" v-if="detailInfo.goodsInfo != null">
            <el-form-item label="验机报告: " style="margin: 2px">{{testValuesFormatter(detailInfo.goodsInfo.testValues)}}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { sellListBill, dataBill, conditionSearch, updateStatus } from "@/api/recovery/bill";
import {listBasicClient} from "@/api/basic/basicClient"
import {getGoods} from "@/api/recovery/goods";
import {getCollect} from "@/api/store/collect"
import {listUser} from "@/api/system/user"
import {listStock} from "@/api/recovery/stock"
import {strTranArray} from "@/utils/tran/shareUtils";
import {listTestValues} from "@/api/basic/testValues"
import $const from "@/utils/websocket/ServerPath";


export default {
  name: "Bill",
  components: {
  },
  data() {
    return {
      /*筛选条件*/
      conditionParams: {
        timeType: 'day',
        hasPayee: 'no'
      },
      /* 筛选结果*/
      conditionData: [],
      /*窗口开关*/
      conditionOpen: false,
      /* 支付详情 多种支付*/
      paymentJson: [
        {type: 1, payee: null, price: 0},
        {type: 2, payee: null, price: 0}
      ],
      /*报价师列表*/
      offerNameOptions: [],
      /*支付方式列表*/
      paymentTypeOptions: $const.PAYMENT_OPTIONS,
      /*收款账户数据字典*/
      payeeOption: [],
      /* 统计数据和开关*/
      dataPrice: {costPrice: 0, sellPrice: 0, profitPrice: 0},
      dataOpen: false,
      //修改时间搜索范围
      updateTimeRange: [],
      //时间搜索范围
      createTimeRange: [],
      //退货商品信息
      outGoodsForm: {},
      //退货开关
      outGoodsOpen: false,
      //验机选项列表
      testValuesList: [],
      //仓库列表
      stockList: [],
      //用户列表
      userList: [],
      //详情信息
      detailInfo: null,
      //详情开关
      detailOpen: false,
      //客户列表
      clientOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 财务账单表格数据
      billList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsId: null,
        billName: null,
        goodsSn: null,
        costPrice: null,
        sellPrice: null,
        buyers: null,
        paymentType: null,
        status: null,
        type: null,
        sellBy: null,
        payee: null,
        offerName: null,
        params: {}
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        billName: [
          { required: true, message: "账单名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getDicts("dayu_offer_teach").then(response => {
      this.offerNameOptions = response.data;
    });
    this.getDicts("recovery_bill_payee").then(response => {
      this.payeeOption = response.data;
    });
    this.getList();
    listUser({}).then(resp => {
      this.userList = resp.rows;
    })
    listStock({}).then(resp => {
      this.stockList = resp.rows;
    })
    listTestValues({}).then(resp => {
      this.testValuesList = resp.rows;
    })
  },
  methods: {
    handleStatus() {
      const ids = this.ids;
      for(let i = 0; i < ids.length; i++) {
        for(let j = 0; j < this.billList.length; j++) {
          if(ids[i] === this.billList[j].billId) {
            if(this.billList[j].status !== 1) {
              this.msgError("数据必须为待审核状态！")
              return
            }
          }
        }
      }
      this.$confirm("确认审核编号为 " + ids + " 的数据吗？", '警告', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        return updateStatus(ids);
      }).then(res => {
        this.getList();
        this.msgSuccess("操作成功!")
      })
    },
    /** 设置行背景颜色 */
    setRowClassName(data) {
      if(data.row.sellPrice < data.row.costPrice) {
        return "bg_red";
      }
      return "";
    },
    /** 前往打印页面*/
    gotoPrinting(row) {
      const billIds = row.billId || this.ids;
      let data = {ids: billIds};
      let buyers = ""; //同一个买家
      let sellBy = ""; //同一个销售人
      let type = null; //同一个账单类型
      for(let i = 0; i < billIds.length; i++) {
        for(let j = 0; j < this.billList.length; j++) {
          if(Number(billIds[i]) === this.billList[j].billId) {
            if(i === 0) {
              buyers = this.billList[j].buyers;
              sellBy = this.billList[j].sellBy;
              type = this.billList[j].type;
              break;
            }
            if(type !== this.billList[j].type) {
              this.msgError("请选择相同账单类型！");
              return
            }
            if(buyers !== this.billList[j].buyers) {
              this.msgError("请选择同一个买家！");
              return
            }
            if(sellBy !== this.billList[j].sellBy) {
              this.msgError("请选择同一个销售人！")
              return
            }
          }
        }
      }
      console.log("data: ", data)
      const url = this.$router.resolve({path: '/bill/printing', query : data})
      window.open(url.href, '_blank')
    },
    conditionChange(e) {
      conditionSearch(this.conditionParams).then(resp => {
        this.conditionData = resp.data;
      })
    },
    /*支付统计窗口*/
    handleCondition() {
      conditionSearch(this.conditionParams).then(resp => {
        this.conditionData = resp.data;
        this.conditionOpen = true;
      })
    },
    setSellPriceChange(e) {
      let price = 0;
      for(let i = 0; i < this.paymentJson.length; i++) {
        if(this.paymentJson[i].price != null) {
          price += Number(this.paymentJson[i].price);
        }
      }
      this.form.sellPrice = price;
    },
    /* 添加一行 支付详情*/
    addPaymentJson() {
      this.paymentJson.push({type: 1, payee: null, price: 0});
    },
    /*删除 一行支付详情*/
    delPaymentJson(key) {
      this.$delete(this.paymentJson, key);
    },
    // 报价师字典翻译
    offerNameFormat(row, column) {
      return this.selectDictLabel(this.offerNameOptions, row.offerName);
    },
    // 收款人字典翻译
    payeeFormatter(row, column) {
      return this.selectDictLabel(this.payeeOption, row.payee);
    },
    closeData() {
      this.dataOpen = false
    },
    openData() {
      this.dataOpen = true;
      this.dataPrice = {costPrice: 0, sellPrice: 0, profitPrice: 0};
      dataBill(this.queryParams).then(resp => {
        if(resp.data != null) {
          this.dataPrice = resp.data;
        }
      })
    },
    /** 修改时间*/
    updateTimeChange(e) {
      if(e == null) {
        this.$delete(this.queryParams.params, 'updateStartTime');
        this.$delete(this.queryParams.params, 'updateEndTime');
        return
      }
      this.$set(this.queryParams.params, 'updateStartTime', e[0]);
      this.$set(this.queryParams.params, 'updateEndTime', e[1]);
    },
    /** 创建时间选项*/
    createTimeChange(e) {
      if(e == null) {
        this.$delete(this.queryParams.params, 'createStartTime');
        this.$delete(this.queryParams.params, 'createEndTime');
        return
      }
      this.$set(this.queryParams.params, 'createStartTime', e[0]);
      this.$set(this.queryParams.params, 'createEndTime', e[1]);
    },
    /** 验机报告 */
    testValuesFormatter(testValues) {
      testValues = testValues == null ? "" : testValues;
      let arr = strTranArray(testValues);
      let res = "";
      for(let i = 0; i < arr.length; i++) {
        for(let j = 0; j < this.testValuesList.length; j++) {
          if(arr[i] === this.testValuesList[j].valuesId) {
            res += "[" + this.testValuesList[j].valuesName + "]-";
            break;
          }
        }
      }
      return res.substring(0, res.length - 1);
    },
    /** 仓库格式 */
    stockFormatter(stockId) {
      for(let i = 0; i < this.stockList.length; i++) {
        if(stockId === this.stockList[i].stockId) {
          return this.stockList[i].stockName;
        }
      }
    },
    /** 用户格式 */
    userFormatter(userId) {
      for(let i = 0; i < this.userList.length; i++) {
        if(userId === this.userList[i].userId) {
          return this.userList[i].nickName;
        }
      }
    },
    /** 打开详情框 */
    async handleDetail(row) {
      this.detailInfo = {
        goodsInfo: null,
        collectInfo: null,
        row: row
      }
      if(row.goodsId != null) {
        await getGoods(row.goodsId).then(resp => {
          this.detailInfo.goodsInfo = resp.data
        })
        if(this.detailInfo.goodsInfo.storeId != null) {
          await getCollect(this.detailInfo.goodsInfo.storeId).then(resp => {
            this.detailInfo.collectInfo = resp.data;
          })
        }

      }
      this.detailOpen = true;
    },
    /** 账单类型 */
    typeFormatter(row) {
      switch (row.type) {
        case 1: return "商品出售";
        case 2: return "自定义账单";
        case 3: return "退货账单";
      }
    },
    /** 查询财务账单列表 */
    getList() {
      this.loading = true;
      sellListBill(this.queryParams).then(response => {
        this.billList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        billId: null,
        goodsId: null,
        billName: null,
        goodsSn: null,
        costPrice: null,
        sellPrice: null,
        profit: null,
        buyers: '零售',
        paymentType: 1,
        status: 0,
        type: null,
        createId: null,
        createBy: null,
        createTime: null,
        updateId: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        sellBy: null,
        payee: null,
        paymentDetail: null
      };
      this.resetForm("form");
      this.paymentJson = [
        {type: 1, payee: null, price: 0},
        {type: 2, payee: null, price: 0}
      ];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.closeData();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.createTimeRange = [];
      this.createTimeChange(null);
      this.updateTimeRange = [];
      this.updateTimeChange(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.billId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加财务账单";
    }
  }
};
</script>

<style>
.el-table .bg_red {
  background-color: rgb(253, 226, 226);
}
</style>
